<script setup lang="ts">
import { onMounted, reactive } from 'vue'
import {
  ElTable,
  ElTableColumn,
  ElForm,
  ElFormItem,
  ElButton,
  ElInput,
  ElCheckbox,
  ElDatePicker,
  ElSelect,
  ElOption,
  ElMessage,
  ElPagination
} from 'element-plus'
import { Dialog } from '@/components/Dialog'
import { useIcon } from '@/hooks/web/useIcon'
import { formatToDate } from '@/utils/dateUtil'
import {
  RetrieveUser,
  CreateNewUser,
  UpdateRowUser,
  RetrieveUserLoginLog
} from '@/api/sysmanage/user'
import { UserDataType, EditUserParams, UserItem } from './types/user'

const plusIcon = useIcon({ icon: 'system-uicons:plus' })

const showLoginData = reactive({
  isShow: false,
  dataLoading: false,
  uid: -1,
  page: 1,
  pageSize: 50,
  totalRows: 0,
  loginLog: []
})

const userData = reactive<UserDataType>({
  kw: '',
  page: 1,
  page_size: 20,
  totalRows: 0,
  userRows: []
})

const editDialogParam = reactive<EditUserParams>({
  isShow: false,
  showTitle: '',
  userTypes: [
    { value: 1, label: '正式用户' },
    { value: 2, label: '注册用户' },
    { value: 3, label: '试用用户' },
    { value: 4, label: '定制用户' }
  ],
  confirmButtonText: '确定添加',
  saveLoading: false
})

const initUserItem = {
  uid: -1,
  phone: '',
  nickname: '',
  username: '',
  user_type: '',
  is_employee: false,
  has_futures_account: false,
  service: '',
  vip_expire: formatToDate(new Date()),
  probation_expire: '',
  password: '',
  is_active: false,
  company: '',
  job: ''
}
const editUserItem = reactive<UserItem>(JSON.parse(JSON.stringify(initUserItem)))

const toShowCreateUserDiag = () => {
  Object.assign(editUserItem, initUserItem)
  editUserItem.uid = -1
  editDialogParam.showTitle = '新建用户'
  editDialogParam.confirmButtonText = '确定新建'
  editDialogParam.isShow = true
}

const toShowEditUserDiag = (user: UserItem) => {
  Object.assign(editUserItem, user)
  editUserItem.uid = user.id
  editDialogParam.showTitle = '编辑用户资料'
  editDialogParam.confirmButtonText = '确定保存'
  editDialogParam.isShow = true
}

const toSaveUserRow = async () => {
  editDialogParam.saveLoading = true
  let resData: any = null
  try {
    if (editUserItem.uid && editUserItem.uid > 0) {
      resData = await UpdateRowUser(editUserItem) // 修改
    } else {
      resData = await CreateNewUser(editUserItem) // 新建
    }
  } catch (error) {
    editDialogParam.saveLoading = false
  }
  if (resData) {
    ElMessage.success({ message: resData.message })
    editDialogParam.saveLoading = false
    editDialogParam.isShow = false
    loadUserList()
  }
}

const loadUserLoginLog = () => {
  RetrieveUserLoginLog(showLoginData.uid, showLoginData.page)
    .then((res) => {
      showLoginData.loginLog = res.data.rows
      showLoginData.totalRows = res.data.total_count
      showLoginData.dataLoading = false
    })
    .catch(() => {
      showLoginData.dataLoading = false
    })
}

const tablePageChange = (p: number) => {
  userData.page = p
  loadUserList()
}
const logPageChange = (p: number) => {
  showLoginData.page = p
  loadUserLoginLog()
}

const tableCellClick = (row: UserItem, column: any) => {
  if (column.property !== 'ssn') return
  // console.log(row, column)
  showLoginData.loginLog = []
  if (!row.id) return
  showLoginData.uid = row.id
  showLoginData.dataLoading = true
  loadUserLoginLog()
  showLoginData.isShow = true
}

const loadUserList = () => {
  RetrieveUser({ kw: userData.kw, page: userData.page, page_size: userData.page_size }).then(
    (res) => {
      userData.userRows = res.data.rows
      userData.totalRows = res.data.total_count
    }
  )
}

const toLoadUserList = () => {
  userData.page = 1
  userData.userRows = []
  userData.totalRows = 0
  loadUserList()
}

onMounted(() => {
  loadUserList()
})
</script>
<template>
  <div class="page-view">
    <div class="actions-box">
      <ElInput
        v-model="userData.kw"
        clearable
        placeholder="输入手机号或系统号查询用户"
        style="margin-right: 10px"
        @change="toLoadUserList"
      />
      <ElButton type="primary" :icon="plusIcon" @click="toShowCreateUserDiag">新建</ElButton>
    </div>
    <ElTable class="table" border stripe :data="userData.userRows" @cell-click="tableCellClick">
      <ElTableColumn prop="id" label="ID" width="100">
        <template #default="scope">
          <div class="edit-column" @click="toShowEditUserDiag(scope.row)">
            <Icon class="edit-icon" icon="svg-icon:box-edit" />
            <div class="row-id">{{ scope.row.id }}</div>
          </div>
        </template>
      </ElTableColumn>
      <ElTableColumn prop="ssn" label="系统号" width="150" />
      <ElTableColumn prop="phone" label="手机" width="170" />
      <ElTableColumn prop="nickname" label="昵称" />
      <ElTableColumn prop="username" label="用户名" />
      <ElTableColumn prop="ut_name" label="类型" width="120" />
      <ElTableColumn prop="probation_expire" label="试用截止" width="120" />
      <ElTableColumn label="公司员工" width="90" align="center">
        <template #default="scope">
          <Icon v-if="scope.row.is_employee" icon="svg-icon:dash-yes" />
        </template>
      </ElTableColumn>
      <ElTableColumn label="公司开户" width="90" align="center">
        <template #default="scope">
          <Icon v-if="scope.row.has_futures_account" icon="svg-icon:dash-yes" />
        </template>
      </ElTableColumn>
      <ElTableColumn label="管理员" width="90" align="center">
        <template #default="scope">
          <Icon v-if="scope.row.is_admin" icon="svg-icon:dash-yes" />
        </template>
      </ElTableColumn>
      <ElTableColumn label="有效" width="70" align="center">
        <template #default="scope">
          <Icon v-if="scope.row.is_active" icon="svg-icon:dash-yes" />
        </template>
      </ElTableColumn>
    </ElTable>
    <div class="page-box">
      <ElPagination
        v-model:current-page="userData.page"
        v-model:page-size="userData.page_size"
        hide-on-single-page
        background
        small
        layout="total,prev,pager,next,jumper"
        :total="userData.totalRows"
        @current-change="tablePageChange"
      />
    </div>
    <!-- 编辑弹窗 -->
    <Dialog v-model="editDialogParam.isShow" :title="editDialogParam.showTitle">
      <ElForm>
        <ElFormItem label="用户手机">
          <ElInput v-model="editUserItem.phone" placeholder="用户的手机号" />
        </ElFormItem>
        <ElFormItem label="用户昵称">
          <ElInput v-model="editUserItem.nickname" placeholder="用户的昵称" />
        </ElFormItem>
        <ElFormItem label="用户姓名">
          <ElInput v-model="editUserItem.username" placehoder="用户的姓名" />
        </ElFormItem>
        <ElFormItem label="客户经理">
          <ElInput v-model="editUserItem.service" placeholder="用户的客户经理" />
        </ElFormItem>
        <ElFormItem label="会员截止">
          <ElDatePicker
            v-model="editUserItem.vip_expire"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </ElFormItem>
        <ElFormItem label="试用截止">
          <ElDatePicker
            v-model="editUserItem.probation_expire"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </ElFormItem>
        <ElFormItem label="用户类型">
          <ElSelect v-model="editUserItem.user_type" style="width: 100%">
            <ElOption
              v-for="t in editDialogParam.userTypes"
              :key="t.value"
              :value="t.value"
              :label="t.label"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="初始密码">
          <ElInput v-model="editUserItem.password" placehoder="设置用户的密码" />
        </ElFormItem>
        <ElFormItem label="我司员工">
          <ElCheckbox v-model="editUserItem.is_employee">是</ElCheckbox>
        </ElFormItem>
        <ElFormItem label="我司开户">
          <ElCheckbox v-model="editUserItem.has_futures_account">是</ElCheckbox>
        </ElFormItem>
        <ElFormItem label="有效用户">
          <ElCheckbox v-model="editUserItem.is_active">是</ElCheckbox>
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton @click="editDialogParam.isShow = false">关闭</ElButton>
        <ElButton @click="toSaveUserRow" :loading="editDialogParam.saveLoading" type="primary">
          {{ editDialogParam.confirmButtonText }}
        </ElButton>
      </template>
    </Dialog>
    <!-- 弹窗登录记录 -->
    <Dialog v-model="showLoginData.isShow" title="用户登录日志">
      <ElTable border stripe v-loading="showLoginData.dataLoading" :data="showLoginData.loginLog">
        <ElTableColumn prop="create_time" label="时间" width="170" />
        <ElTableColumn prop="origin_ip" label="IP地址" width="150" />
        <ElTableColumn prop="country" label="国家" />
        <ElTableColumn prop="province" label="省份" />
        <ElTableColumn prop="district" label="地区" />
        <ElTableColumn prop="isp_name" label="运营商" />
      </ElTable>
      <div class="page-box">
        <ElPagination
          v-model:current-page="showLoginData.page"
          v-model:page-size="showLoginData.pageSize"
          hide-on-single-page
          background
          small
          layout="total,prev,pager,next,jumper"
          :total="showLoginData.page"
          @current-change="logPageChange"
        />
      </div>
    </Dialog>
  </div>
</template>
<style scoped lang="less">
.page-view {
  .actions-box {
    margin-bottom: 5px;
    display: flex;
    justify-content: flex-end;
  }
  .table {
    .edit-column {
      display: flex;
      align-items: center;
      cursor: pointer;
      .edit-icon {
        margin-right: 5px;
      }
    }
  }
  .page-box {
    margin-top: 5px;
  }
}
</style>
